package com.simpou.commons.utils.validation;

import com.simpou.commons.utils.behavior.Validator;
import com.simpou.commons.utils.exception.model.RuleViolation;
import com.simpou.commons.utils.string.RegexHelper;
import static com.simpou.commons.utils.validation.LocaleValidator.isValid;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Validador de IP.
 *
 * @author Jonas Pereira
 * @since 2011-06-25
 * @version 2013-05-31
 */
public final class IPValidator implements Validator<String> {
    /**
     * Pattern.
     */
    private static final Pattern PATTERN = Pattern.compile(RegexHelper.IP);

    /**
     * <p>isValid.</p>
     *
     * @param value Valor.
     * @return Se valor é válido. Valor null é considerado válido.
     */
    public static RuleViolation isValid(final String value) {
        final RuleViolation violation;

        if ((value == null) || value.isEmpty()) {
            violation = null;
        } else if ((value.length() < 7) || (value.length() > 15)) {
            violation = Violation.INVALID_LENGTH;
        } else {
            Matcher m = PATTERN.matcher(value);

            if (m.matches()) {
                violation = null;
            } else {
                violation = Violation.NOT_MATCH;
            }
        }

        return violation;
    }

    /**
     * @param ip IP a ser validado.
     */
    @Override
    public RuleViolation validate(final String ip) {
        return isValid(ip);
    }
    @Getter
    @AllArgsConstructor
    public enum Violation implements RuleViolation {
        NOT_MATCH("IP doesnt match " + RegexHelper.IP),
        INVALID_LENGTH("IP must have between 7 and 15 characters.");
        
        private String msg;

        @Override
        public String getType() {
            return this.name();
        }
    }
}
